import {PlusOutlined} from '@ant-design/icons';
import {Button, Tag, message, Input, Drawer, InputNumber, Select, Form, DatePicker, Divider, Modal} from 'antd';
import {ExclamationCircleOutlined} from '@ant-design/icons';
import React, {useState, useRef, useEffect} from 'react';
import {PageContainer, FooterToolbar} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import StockProductForm from './components/StockProductForm';
import {
  productIntoWarehouse,
  queryWarehouseProduct,
  queryWarehouseProductHistory,
  productOutWarehouse,
  productRepairWarehouse,
  productScrapWarehouse,
  queryShipmentByPrdDay
} from "@/services/warehouse";
import moment from "moment";
import {queryShipOrder} from "@/services/order";
import {
  addAccount, addEqp,
  queryAccount, queryDepartment,
  queryEqp,
  queryRole, queryStaff, removeAccount, removeEqp,
  resetPassword,
  updateAccount,
  updateAccountStatus, updateEqp
} from "@/services/system";
import AccountForm from "@/pages/system/account-manage/components/AccountForm";

const initRecord = {
  equipmentName: '',
  equipmentCode: '',
  id: ''
}

const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [roleData, setRoleData] = useState([]);
  const [staffData, setStaffData] = useState([]);
  const [selectedRecord, setSelectedRecord] = useState({});
  const [targetKeys, setTargetKeys] = useState([]);
  const [selectedKeys, setSelectedKeys] = useState([]);
  const [formTitle, setFormTitle] = useState('新增设备');
  const actionRef = useRef();
  const [formRef] = Form.useForm();
  const [row, setRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);
  const {Option} = Select;
  const [departments, setDeartments] = useState([]);
  const handleUpdateModalVisible = (record) => {
    setTargetKeys(record.roleIds)
    formRef.setFieldsValue({
      ...record
    })
    setSelectedRecord(record)
    setFormTitle('更新设备')
    handleModalVisible(true)
  }
  const handleCreateModalVisible = () => {
    setTargetKeys([])
    formRef.setFieldsValue({
      ...initRecord
    })
    setFormTitle('新增设备')
    handleModalVisible(true)
  }

  const getRoleData = async ()=>{
    await queryRole({
      pageNum: 1,
      pageSize: 9999
    }).then(res=>{
      if(res && res.status === '0') {
        setRoleData(res.result.records)
      }
    })
  }


  const handleAccountStatus = async (record) => {
    await updateAccountStatus({
      userId: record.id,
      sysUserStatus: record.sysUserStatus === 0? 1: 0
    })
    if (actionRef.current) {
      actionRef.current.reload();
    }
  }

  const handleResetPassword = async (record) => {
    await resetPassword({...record}).then(res=>{
      if (res && res.status === '0') {
        message.success("密码重置成功")
      }else {
        message.error(res.message)
      }
    })
  }

  const handleAdd = async (fields) => {
    const hide = message.loading('正在添加');

    try {
      await addEqp({
        ...fields
      }).then(res=>{
        if (res.code === '0') {
          message.success('设备添加成功');
        }
      });
      hide();
      return true;
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      return false;
    }
  };

  const handleUpdate = async (fields) => {
    const hide = message.loading('正在配置');

    try {
      fields.id = selectedRecord.id
      await updateEqp({
        ...fields,
        roleIds: targetKeys
      });
      hide();
      message.success('配置成功');
      return true;
    } catch (error) {
      hide();
      message.error('配置失败请重试！');
      return false;
    }
  };

  const handleRemove = async (selectedRows) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;

    try {
      await removeEqp({
        idList: [
          selectedRows.id
        ]
      }).then(res=>{
        if (res && res.status === '0') {
          hide();
          if (actionRef.current) {
            actionRef.current.reload();
          }
          message.success('删除成功，即将刷新');
        }else {
          message.error(res.message)
        }
      });
      return true;
    } catch (error) {
      hide();
      message.error('删除失败，请重试');
      return false;
    }
  };

  const handleStaffNameSearch = async (v)=>{
    await queryStaff({
      pageNum: 1,
      pageSize: 9999,
      staffName: v
    }).then(res=>{
      //console.log((res)
      if(res && res.status === '0') {
        setStaffData(res.result.records)
      }
    })
  }

  const deleteConfig = (record) => {
    Modal.confirm({
      title: '注意',
      icon: <ExclamationCircleOutlined/>,
      content: `是否要删除的设备${record.equipmentName}？`,
      okText: '确认',
      cancelText: '取消',
      onOk: ()=>{
        handleRemove(record)
      }
    });
  };

  const resetConfig = (record) => {
    Modal.confirm({
      title: '注意',
      icon: <ExclamationCircleOutlined/>,
      content: `是否要重置设备${record.account}的密码？`,
      okText: '确认',
      cancelText: '取消',
      onOk: ()=>{
        handleResetPassword(record)
      }
    });
  };

  const onChange = (nextTargetKeys, direction, moveKeys) => {
    //console.log(('targetKeys:', nextTargetKeys);
    //console.log(('direction:', direction);
    //console.log(('moveKeys:', moveKeys);
    setTargetKeys(nextTargetKeys);
  };

  const onSelectChange = (sourceSelectedKeys, targetSelectedKeys) => {
    //console.log(('sourceSelectedKeys:', sourceSelectedKeys);
    //console.log(('targetSelectedKeys:', targetSelectedKeys);
    setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys]);
  };

  const onScroll = (direction, e) => {
    //console.log(('direction:', direction);
    //console.log(('target:', e.target);
  };

  const getDepartment = async()=>{
    await queryDepartment({
      current: 1,
      size: 9999
    }).then(res=>{
      if(res && res.status === '0') {
        setDeartments(res.result.records)
      }
    })
  }

  useEffect(()=>{
    getDepartment();
  }, [])

  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      hideInForm: true,
      hideInSearch: true,
      render: (text, record, index, action) => {
        return `${index + 1}`
      }
    },
    {
      title: '设备名称',
      dataIndex: 'equipmentName',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            max: 32,
            message: '最大长度为32'
          },
        ],
      },
    },
    {
      title: '设备编码',
      dataIndex: 'equipmentCode',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            max: 32,
            message: '最大长度为32'
          },
        ],
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a onClick={() => setRow(record)}>
          详情
        </a>,
        <Divider type="vertical"/>,
        <a onClick={() => handleUpdateModalVisible(record)}>修改</a>,
        <Divider type="vertical"/>,
        <a onClick={() => deleteConfig(record)}>删除</a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button type="primary" onClick={() => handleCreateModalVisible()}>
            <PlusOutlined/> 新建设备
          </Button>,
        ]}
        request={async (params, sorter, filter) => {
          const param = {...params, size: params.pageSize};
          const res = await queryEqp(param)
          return {
            data: res.result.records,
            success: true,
            total: res.result.total
          }
        }}
        columns={columns}
      />
      <AccountForm title={formTitle} onCancel={() => handleModalVisible(false)} modalVisible={createModalVisible}>
        <ProTable
          onSubmit={async (value) => {
            const success = formTitle=== '新增设备'? await handleAdd(value): await handleUpdate(value);

            if (success) {
              handleModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          form={{
            form: formRef,
            layout: 'horizontal',
            labelAlign: 'left'
          }}
          rowKey="key"
          type="form"
          columns={columns}
        />
      </AccountForm>

      <Drawer
        width={600}
        visible={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.equipmentName && (
          <ProDescriptions
            column={2}
            title={row?.equipmentName}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.equipmentName,
            }}
            columns={columns}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
